package io.github.jesse205.transferstation.lite.fragments;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.support.annotation.Nullable;
import android.util.Log;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import io.github.jesse205.transferstation.lite.BuildConfig;
import io.github.jesse205.transferstation.lite.DragDropApplication;
import io.github.jesse205.transferstation.lite.DragDropPreferences;
import io.github.jesse205.transferstation.lite.R;
import io.github.jesse205.transferstation.lite.helpers.PermissionsHelper;
import io.github.jesse205.transferstation.lite.managers.DragDropManager;
import io.github.jesse205.transferstation.lite.sources.AppSource;
import io.github.jesse205.transferstation.lite.sources.PanelSource;

public class RootFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
    private static final String TAG = "RootFragment";
    private DragDropApplication application;
    private AppSource appSource;
    private PanelSource panelSource;
    private SwitchPreference enableAppPreference;
    private SwitchPreference showPanelPreference;
    private final PropertyChangeListener panelChangeListener = evt -> {
        onPanelVisibleChange((Boolean) evt.getNewValue());
    };
    private Preference clearPanelDataPreference;
    private SwitchPreference enableDropPagePreference;
    private DragDropManager dragDropManager;
    private final PropertyChangeListener dragDropManagerListener = this::onDragDropManagerChange;
    private final PropertyChangeListener appEnabledChangeListener = evt -> {
        onAppEnabledChange((Boolean) evt.getNewValue());
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.root_preferences);
        application = (DragDropApplication) getContext().getApplicationContext();

        enableAppPreference = (SwitchPreference) findPreference(DragDropPreferences.KEY_ENABLE_APP);
        Preference adsorbPreference = findPreference(DragDropPreferences.KEY_ADSORB);
        showPanelPreference = (SwitchPreference) findPreference(DragDropPreferences.KEY_SHOW_PANEL);
        Preference versionPreference = findPreference(DragDropPreferences.KEY_VERSION);
        clearPanelDataPreference = findPreference(DragDropPreferences.KEY_CLEAR_PANEL_DATA);
        Preference notePreference = findPreference(DragDropPreferences.KEY_NOTE);
        enableDropPagePreference = (SwitchPreference) findPreference(DragDropPreferences.KEY_ENABLE_DROP_PAGE);
        versionPreference.setSummary(String.format("%s (%s)", BuildConfig.VERSION_NAME,
                BuildConfig.VERSION_CODE));
        enableAppPreference.setOnPreferenceChangeListener(this);
        adsorbPreference.setOnPreferenceChangeListener(this);
        showPanelPreference.setOnPreferenceChangeListener(this);
        clearPanelDataPreference.setOnPreferenceClickListener(this);
        enableDropPagePreference.setOnPreferenceClickListener(this);
        notePreference.setOnPreferenceClickListener(this);
        appSource = application.getAppSource();
        appSource.addListener(appEnabledChangeListener);

        // 如果启动时就没有开启中转站，那么禁用显示面板选项和清除面板数据
        onAppEnabledChange(appSource.getState());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        appSource.removeListener(appEnabledChangeListener);
        if (panelSource != null)
            panelSource.removeListener(panelChangeListener);
        if (dragDropManager != null)
            dragDropManager.removeListener(dragDropManagerListener);
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        Context context = getContext();
        switch (preference.getKey()) {
            case DragDropPreferences.KEY_ENABLE_APP:
                if ((boolean) newValue &&
                        !PermissionsHelper.askDrawOverlaysPermission(getActivity(), 0)) {
                    return false;
                }
                application.setAppEnabled((Boolean) newValue);
                return true;
            case DragDropPreferences.KEY_ADSORB:
                application.setAdsorb((boolean) newValue);
                break;
            case DragDropPreferences.KEY_SHOW_PANEL:
                if (application.getAppService() != null)
                    if ((boolean) newValue)
                        application.getAppService().openPanel();
                    else
                        application.getAppService().closePanel();
                return false;
            case DragDropPreferences.KEY_ENABLE_DROP_PAGE:
                if (application.getAppService() != null) {
                    return false;
                }

        }
        return true;
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        switch (preference.getKey()) {
            case DragDropPreferences.KEY_CLEAR_PANEL_DATA:
                if (application.getAppService() != null) {
                    application.getAppService().clearPanelData();
                }
                break;
            case DragDropPreferences.KEY_NOTE:
                new AlertDialog.Builder(getContext())
                        .setTitle(R.string.note)
                        .setMessage(R.string.note_content)
                        .setPositiveButton(android.R.string.ok, null)
                        .show();
                break;
        }
        return false;
    }

    public void onAppEnabledChange(boolean newState) {
        Log.d(TAG, "onAppEnabledChange: " + newState);

        enableAppPreference.setChecked(newState);
        showPanelPreference.setEnabled(newState);
        enableDropPagePreference.setEnabled(!newState);

        if (newState) {
            dragDropManager = DragDropManager.getInstance(getContext());
            // 清除内容的前提是有内容
            clearPanelDataPreference.setEnabled(dragDropManager.hasData());
            addPanelVisibleChangeListener();
            dragDropManager.addListener(dragDropManagerListener);
        } else {
            clearPanelDataPreference.setEnabled(false);
            if (panelSource != null)
                panelSource.removeListener(panelChangeListener);
            if (dragDropManager != null)
                dragDropManager.removeListener(dragDropManagerListener);
            panelSource = null;
            dragDropManager = null; // 销毁的事归 service 管
        }
    }

    private void onPanelVisibleChange(Boolean newState) {
        showPanelPreference.setChecked(newState);
    }

    public void addPanelVisibleChangeListener() {
        if (application.getAppService() != null) {
            panelSource = application.getAppService().getPanelChangeSource();
            panelSource.addListener(panelChangeListener);
            onPanelVisibleChange((Boolean) panelSource.getState());
            Log.d(TAG, "addPanelVisibleChangeListener: add success");
        } else {
            Log.d(TAG, "addPanelVisibleChangeListener: add failed");

        }
    }

    public void onDragDropManagerChange(PropertyChangeEvent evt) {
        getActivity().runOnUiThread(() -> {
            clearPanelDataPreference.setEnabled(dragDropManager.hasData());
        });

    }

}
